package web

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/req"
	"commerce/vo"
	"encoding/json"
	"net/http"
	"strconv"
)

/* 此文件是 app 商品收藏 请求 */

func AddOrDeleteCollect(w http.ResponseWriter, r *http.Request) {

	var collectReq req.CollectReq
	err := json.NewDecoder(r.Body).Decode(&collectReq)

	if err != nil {
		common.Error.Printf("AddOrDeleteCollect err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	appUser := r.Context().Value(APP)

	if appUser == nil {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	member, ok := appUser.(*AppUser)
	if !ok {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	var opType = 1
	// 之前没有收藏，点击进来，表示 收藏操作
	if collectReq.HasCollect == 0 {
		_, err = data.AddGoodsCollect(model.GoodsCollect{MemberId: member.Mid, SkuId: collectReq.ValueId})
	} else {
		opType = 0
		err = data.DeleteGoodsCollect(member.Mid, collectReq.ValueId)
	}
	if err != nil {
		common.Error.Printf("2.AddOrDeleteCollect err:%v", err)
		j, _ := json.Marshal(vo.Err("系统错误，请稍候再试！"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok(opType))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func ListCollect(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	typeId, _ := strconv.Atoi(r.PostFormValue("typeId"))
	common.Info.Println("ListCollect:typeId: ", typeId)

	skus, err := data.ListCollectGoods(member.Mid)
	if err != nil {
		common.Error.Printf("2.ListCollect err:%v", err)
		j, _ := json.Marshal(vo.Err("系统错误，请稍候再试！"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	var skuList = make([]vo.AppSku, 0)
	if skus != nil && len(skus) > 0 {
		for _, k := range skus {
			skuList = append(skuList, vo.AppSku{Id: k.Id, Name: k.Name, MainImg: k.MainImg, RetailPrice: k.RealPrice, Desc: k.Description})
		}
	}
	j, _ := json.Marshal(vo.Ok(skuList))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}
